/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 题目收藏接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const {
  QuestionFav,
  Question,
  Paper,
  ExamHistory,
  Exam
} = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { uniqueArrayByKeyWithCount } = require('../utils')
const { delModel, sortModel } = require('@/utils/controllerCommon')
/**
 * 列表查询题目收藏接口
 * @param {*} ctx
 * @returns
 */
module.exports.listQuestionFav = async (ctx) => {
  const { userId, paperId, examId } = ctx.query
  const whereCondition = {
    userId: ctx.user.id
  }
  if (userId !== undefined) {
    whereCondition.userId = userId
  }
  if (paperId !== undefined) {
    whereCondition.paperId = paperId
  }
  if (examId !== undefined) {
    whereCondition.examId = examId
  }
  const orderCondition = [['sort']]

  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await QuestionFav.findAndCountAll({
    where: whereCondition,
    include: [
      {
        model: Question
      },
      {
        model: Paper
      }
    ],
    offset: +start,
    limit: +pageSize,
    order: orderCondition,
    distinct: true
  })

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

/**
 * 列表查询题目收藏接口
 * @param {*} ctx
 * @returns
 */
module.exports.listFavPaper = async (ctx) => {
  const { examId } = ctx.query
  const whereCondition = { examId, userId: ctx.user.id }

  const orderCondition = [['sort']]

  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await QuestionFav.findAndCountAll({
    where: whereCondition,
    attributes: ['id', 'paperId', 'sort', 'examId'],
    include: [
      {
        model: Paper,
        include: [
          {
            model: ExamHistory
          }
        ]
      },
      {
        model: Exam
      }
    ],
    order: orderCondition,
    distinct: true
  })

  const finaRows = uniqueArrayByKeyWithCount(rows, 'paperId')

  ctx.body = R.success({
    page,
    pageSize,
    total: finaRows.length,
    pages: Math.ceil(count / pageSize),
    items: finaRows
  })
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 创建题目收藏接口
 * @param {*} ctx
 */
module.exports.createQuestionFav = async (ctx) => {
  const { questionId } = ctx.request.body
  const t = await Mysequelize.transaction()
  const nextId = generatId()
  const sort = await QuestionFav.max('sort')

  let question = await Question.findByPk(BigInt(questionId))
  let paperId = question.paperId
  let aPaper = await Paper.findByPk(paperId)
  let examId = aPaper.examId

  // 看收藏记录是否存在，如果存在，则是取消收藏
  let aQuestionFav = await QuestionFav.findOne({
    where: {
      userId: ctx.user.id,
      questionId
    }
  })

  // 不管取消收藏还是添加收藏，都需要删除paper对应的作答记录
  if (aQuestionFav) {
    try {
      await QuestionFav.destroy({
        where: {
          userId: ctx.user.id,
          questionId
        },
        transaction: t
      })

      await ExamHistory.destroy({
        where: {
          userId: ctx.user.id,
          paperId,
          type: 3
        },
        transaction: t
      })
      await t.commit()
      ctx.body = R.success()
    } catch (error) {
      await t.rollback()
      ctx.body = R.error(ERROR_USER_CODE.QUESTION_FAV_CREATE_ERROR)
    }
  } else {
    let createObj = {
      id: nextId,
      userId: ctx.user.id,
      questionId,
      paperId,
      examId,
      sort: sort + 1,
      createUser: ctx.user.id,
      updateUser: ctx.user.id
    }
    try {
      // 到这里可以进行题目收藏的添加了,排序字段默认是最大值
      const questionFav = await QuestionFav.create(createObj, {
        transaction: t
      })
      await ExamHistory.destroy({
        where: {
          userId: ctx.user.id,
          paperId,
          type: 3
        },
        transaction: t
      })
      await t.commit()
      ctx.body = R.success()
    } catch (error) {
      await t.rollback()
      ctx.body = R.error(ERROR_USER_CODE.QUESTION_FAV_CREATE_ERROR)
    }
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 题目收藏，取消收藏接口
 * @param {*} ctx
 *
 */
// module.exports.cancelFav=async(ctx)=>{
//   const { questionId, paperId } = ctx.request.body
//   const t = await Mysequelize.transaction()
// }

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除题目收藏接口
 * @param {*} ctx
 */
module.exports.delQuestionFavs = async (ctx) => {
  await delModel(
    QuestionFav,
    ERROR_USER_CODE.QUESTION_FAV_DEL_ERROR,
    'questionFavIds'
  )(ctx)
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 题目收藏排序接口
 * @param {*} ctx
 */
module.exports.sortQuestionFavs = async (ctx) => {
  // 传递的题目收藏ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    QuestionFav,
    ERROR_USER_CODE.QUESTION_FAV_SORT_ERROR,
    'questionFavIds'
  )(ctx)
}

/**
 * 检验用户是否收藏了某个题目
 */

module.exports.checkQuestionFav = async (ctx) => {
  const { questionId } = ctx.request.body
  const aQuestionFav = await QuestionFav.findOne({
    where: {
      userId: ctx.user.id,
      questionId
    }
  })
  if (aQuestionFav) {
    ctx.body = R.success({
      isFav: true
    })
  } else {
    ctx.body = R.success({
      isFav: false
    })
  }
}
